package com.han.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.han.pojo.Role;
import com.han.pojo.User;
import com.han.service.role.RoleService;
import com.han.service.role.RoleServiceImpl;
import com.han.service.user.UserService;
import com.han.service.user.UserServiceImpl;
import com.han.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class UpdateServlet extends HttpServlet {
    private UserService userService;
    public UpdateServlet(){
        this.userService = new UserServiceImpl();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("savepwd") && method != null) {
            this.updatePwd(req, resp);
        } else if (method.equals("pwdmodify") && method != null){
            this.verifypwd(req,resp);
        } else if (method.equals("query")){
            this.query(req,resp);
        } else if (method.equals("add")){
            this.addUser(req, resp);
        } else if (method.equals("getrolelist")){
            this.getRoleList(req, resp);
        } else if (method.equals("ucexist")){
            this.verifyUserCode(req, resp);
        } else if (method.equals("deluser")){
            this.deleteUser(req, resp);
        } else if (method.equals("modify")){
            this.ModifyUser(req, resp);
        } else if (method.equals("modifyexe")){
            try {
                this.modifyUser(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object login = req.getSession().getAttribute("login");
        String newpassword = req.getParameter("newpassword");
        if (login!=null&&newpassword!=null){
            int i = userService.updateUser(((User)login).getId(),newpassword);
            if (i!=0){
                req.setAttribute("message", "密码修改成功，请退出，使用新密码登录");
                // 密码修改成功,移除session(移除后不能再次修改密码,建议不移除)
                req.getSession().removeAttribute("login");
            } else {
                // 密码修改失败
                req.setAttribute("message", "密码修改失败");
            }
        } else {
            // 密码修改有问题
            req.setAttribute("message", "新密码有问题");
        }
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req, resp);
    }

    //验证旧密码
    public void verifypwd(HttpServletRequest req, HttpServletResponse resp){
        Object login = req.getSession().getAttribute("login");
        String oldpassword = req.getParameter("oldpassword");
        Map<String,String> resultMap = new HashMap<String, String>();
        if(login==null) {//session失效，session过期了
            resultMap.put("result","seesionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User)login).getUserPassword();//seesion中的用户密码
            if(oldpassword.equals(userPassword)) {
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查询用户
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //用户类型下拉框
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);

        //用户分页
        int pageSize = 5;//设置页面容量
        int currentPageNo = 1;//当前页码
        String queryUserName = req.getParameter("queryname");//模糊查询的用户名字
        String temp = req.getParameter("queryUserRole");//查询的用户类型
        String pageIndex = req.getParameter("pageIndex");//当前页数
        int queryUserRole = 0;//查询的用户类型
        if (!StringUtils.isNullOrEmpty(temp)){
            queryUserRole = Integer.parseInt(temp);//将String类型转化为整数
        }
        if(pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }
        int totalCount	= userService.getUserCount(queryUserName,queryUserRole);//用户总数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        //调用方法计算总共页数
        pageSupport.setTotalPageCountByRs();
        int totalPageCount = pageSupport.getTotalPageCount();
        //控制首页和尾页
        //如果页面小于 1 就显示第一页的东西
        if(currentPageNo < 1) {
            currentPageNo = 1;
        }else if(currentPageNo > totalPageCount) {//如果页面大于了最后一页就显示最后一页
            currentPageNo =totalPageCount;
        }
        //获取用户信息
        List<User> userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        req.setAttribute("userList", userList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);
        req.setAttribute("queryUserName", queryUserName);
        req.setAttribute("queryUserRole", queryUserRole);
        req.getRequestDispatcher("/jsp/userlist.jsp").forward(req,resp);
    }

    //添加用户
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        int gender = Integer.parseInt(req.getParameter("gender"));
        String bir = req.getParameter("birthday");
        Date birthday= null;
        try {
            birthday = new SimpleDateFormat("yyyy-MM-dd").parse(bir);
        } catch (Exception e){
            e.printStackTrace();
        }
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        int userRole = Integer.parseInt(req.getParameter("userRole"));
        List<Object> list = new ArrayList<Object>();
        list.add(userCode);
        list.add(userName);
        list.add(userPassword);
        list.add(userRole);
        list.add(gender);
        list.add(birthday);
        list.add(phone);
        list.add(address);
        int i = userService.addUser(list);
        if (i > 0){

            resp.sendRedirect("/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }

    //添加用户的下拉框
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp){
        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        try {
            resp.setContentType("application/josn");
            PrintWriter writer = null;
            writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(roleList));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //验证用户是否存在
    public void verifyUserCode(HttpServletRequest req, HttpServletResponse resp){
        String userCode = req.getParameter("userCode");
        Map<String,String> map = new HashMap<String, String>();
        User login = userService.login(userCode);
        if (login != null){
            map.put("userCode","exist");
        } else {
            map.put("userCode","correct");
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    //删除用户
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        Map<String,String> map = new HashMap<String, String>();
        boolean is = userService.deleteUser(Integer.parseInt(id));
        if (is){
            map.put("delResult","true");
        } else {
            map.put("delResult","false");
        }
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    //修改用户
    public void ModifyUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        User user = null;
        user = userService.getUserById(Integer.parseInt(uid));
        req.setAttribute("user",user);
        req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
    }

    public void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws ParseException, IOException, ServletException {
        String uid = req.getParameter("uid");
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        User login = (User) req.getSession().getAttribute("login");
        User user = new User();
        user.setUserName(userName);
        user.setGender(Integer.parseInt(gender));
        user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.parseInt(userRole));
        user.setModifyBy(login.getId());
        user.setId(Integer.parseInt(uid));
        System.out.println("servlet层测试："+user);
        int i = userService.ModifyUser(user);
        if (i > 0){
            resp.sendRedirect("/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }
}
